<template>
  <div class="box">
    <i class="el-icon-circle-close" @click="del"></i>
    <div class="block" @click="pickImg">
      <input
        v-show="false"
        ref="ipt"
        @change="upload"
        type="file"
        accept="image/*"
      />
      <span v-if="!imgSrc" class="demonstration">上传图片</span>
      <img v-else :src="imgSrc" alt="" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'UploadImg',
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      imgSrc: ''
    }
  },
  methods: {
    pickImg () {
      this.$refs.ipt.click()
    },
    upload (e) {
      const fr = new FileReader()
      fr.readAsDataURL(e.target.files[0])
      fr.onload = (e) => {
        if (e.target.result) {
          const obj = { ...this.item, img: e.target.result }
          this.$emit('imgHasDone', obj)
          this.imgSrc = e.target.result
        }
      }
    },
    del () {
      this.imgSrc = ''
    }
  }

}
</script>

<style lang='scss' scoped>
.box {
  position: relative;
  box-sizing: content-box;
  width: 80px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 5px;
  margin-left: 5px;
  i {
    position: absolute;
    z-index: 9;
    top: -7px;
    right: -7px;
    color: #dcdfe6d5;
    background-color: #fff;
    border-radius: 50%;
  }
}
.block {
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: 5px;
  img,
  .el-image {
    width: 110%;
    height: 110%;
    vertical-align: baseline;
  }
}
</style>
